// 包名
package com.example.pagesldertablistdemo.slice;
// 引入模块
import com.example.pagesldertablistdemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.PageSlider;
import ohos.agp.components.TabList;
import java.util.ArrayList;

public class MainAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        // 数据初始化
        setupDataList();
        // TabList初始化
        setupTabList();
        // PageSlider初始化
        setupPageSlider();
    }
    // 定义私有属性
    private TabList tabList;
    private PageSlider pageSlider;
    private ArrayList<String> datalist;
    // 数据初始化方法
    private void setupDataList() {
        datalist = new ArrayList<>();
        datalist.add("综合新闻");
        datalist.add("时政要闻");
        datalist.add("体育新闻");
        datalist.add("娱乐新闻");
    }
    // TabList初始化方法
    private void setupTabList() {
        // 获取组件
        tabList = (TabList) findComponentById(ResourceTable.Id_tablsit);
        // 循环创建Tab标签
        for (int i = 0; i < datalist.size(); i++) {
            TabList.Tab tab = tabList.new Tab(getContext());
            tab.setText(datalist.get(i));
            tabList.addTab(tab);
        }
        // 默认选中第一个标签
        tabList.selectTabAt(0);
        // 设置选中标签的监听
        tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
            @Override
            public void onSelected(TabList.Tab tab) {
                // 选中某个标签后，设置pageSlider滚动到指定位置
                pageSlider.setCurrentPage(tab.getPosition(), true);
            }
            @Override
            public void onUnselected(TabList.Tab tab) { }
            @Override
            public void onReselected(TabList.Tab tab) { }
        });
    }
    // 初始化PageSlider的方法
    private void setupPageSlider() {
        // 获取组件
        pageSlider = (PageSlider) findComponentById(ResourceTable.Id_pageslider);
        // 设置数据源
        pageSlider.setProvider(new MainAbilityProvider(datalist,getContext()));
        // 设置页面切换的监听
        pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) { }
            @Override
            public void onPageSlideStateChanged(int i) { }
            @Override
            public void onPageChosen(int i) {
                // 页面切换后，对应改变选中的TabList标签
                tabList.selectTabAt(i);
            }
        });
    }
}
